package com.sky.service.impl;

import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import static com.sky.entity.Orders.COMPLETED;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO selectT(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = getLocalDates(begin, end);

        List<BigDecimal> bigDecimals = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            BigDecimal bigDecimal = reportMapper.selectT(beginTime, endTime, COMPLETED);
            if (ObjectUtils.isEmpty(bigDecimal)) {
                bigDecimal = new BigDecimal(0);
            }

            bigDecimals.add(bigDecimal);
        }


        String turnoverList = StringUtils.join(bigDecimals, ",");
        String dateList = StringUtils.join(localDateList, ",");


        return new TurnoverReportVO(dateList, turnoverList);
    }

    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!(begin.toString().equals(end.toString()))) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        return localDateList;
    }

    @Override
    public UserReportVO selectU(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = getLocalDates(begin, end);


        List<Long> userIdsA = new ArrayList<>();
        List<Long> userIdsI = new ArrayList<>();

        for (LocalDate localDate : localDates) {
            //   LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //每天算上之前全部的用户
            Long A = userMapper.selectU(null, endTime);
            userIdsA.add(A);
            //   LocalDateTime beginTime2 = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
            LocalDateTime endTime2 = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);
            //前一天算上之前全部的用户
            Long A2 = userMapper.selectU(null, endTime2);
            //每天新增的用户
            Long I = A - A2;
            userIdsI.add(I);

        }

        String userIda = StringUtils.join(userIdsA, ",");
        String userIdi = StringUtils.join(userIdsI, ",");
        String dateList = StringUtils.join(localDates, ",");


        return new UserReportVO(dateList, userIda, userIdi);


    }

    @Override
    public OrderReportVO selectO(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = getLocalDates(begin, end);


        List<Long> list = new ArrayList<>();
        List<Long> list2 = new ArrayList<>();


        for (LocalDate localDate : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //查询每日的所有订单
            Long orderCountList = reportMapper.selectO(beginTime, endTime, null);

            //每日有效订单
            Long validOrderCountList = reportMapper.selectO(beginTime, endTime, COMPLETED);
            list.add(orderCountList);
            list2.add(validOrderCountList);

        }

        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        //订单总数
        Integer totalOrderCount = Math.toIntExact(reportMapper.selectO(beginTime, endTime, null));

        //有效订单总数
        Integer validOrderCount = Math.toIntExact(reportMapper.selectO(beginTime, endTime, COMPLETED));

        //订单完成率   俩个Integer的值求出double的值

        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        String dateList = StringUtils.join(localDates, ",");
        String orderCountList = StringUtils.join(list, ",");
        String validOrderCountList = StringUtils.join(list2, ",");

        return new OrderReportVO(dateList, orderCountList, validOrderCountList, totalOrderCount, validOrderCount, orderCompletionRate);

    }

    @Override
    public SalesTop10ReportVO selectS(LocalDate begin, LocalDate end) {
//        开始
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
//        结束
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<Long> orderIds = orderMapper.selectByTime(beginTime, endTime);


        List<SalesTop10ReportVOItem> items = orderDetailMapper.getDishNameReportAndNumberReport(orderIds);

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();

/*
        StringBuilder nameList = new StringBuilder();
        StringBuilder numberList = new StringBuilder();
        for (String key : map.keySet()) {
            nameList.append(key+",");
            numberList.append(map.get(key)+",");
        }
        nameList.deleteCharAt(nameList.length()-1);
        numberList.deleteCharAt(numberList.length()-1);
        salesTop10ReportVO.setNameList(nameList.toString());
        salesTop10ReportVO.setNumberList(numberList.toString());
        */
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<Long> numberList = new ArrayList<>();

        for (SalesTop10ReportVOItem item : items) {
            nameList.add(item.getName());
            numberList.add(item.getNumber());
        }
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList, ","));
        salesTop10ReportVO.setNameList(StringUtils.join(nameList, ","));

        return salesTop10ReportVO;

//        List<LocalDate> localDates = getLocalDates(begin, end);
//
//        for (LocalDate localDate : localDates) {
//            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
//            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
//
//
//            orderDetailMapper.selectS(beginTime, endTime, )
//        }


    }

    @Override
    public void exportE(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.selectB(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.selectB(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}



